package org.zjt.platform.spring.boot.example.service.imp;

import org.zjt.platform.spring.boot.example.service.IRabbitMsgService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zjt.platform.spring.boot.example.service.IRabbitMsgService;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:
 * @Package org.zjt.platform.spring.boot.example.service.imp
 * @date 2018/3/14 14:23
 * @see
 */
@Service
@Slf4j
public class RabbitMsgServiceImpl implements IRabbitMsgService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitTemplate manualRabbitTemplate;

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    private final static  String AUTO_QUEUE = "rabbitmq-auto";

    private final static  String MANUAL_QUEUE = "rabbitmq-manual";


    /**
     * 接受自动消息确认的消息
     * @param message
     * @throws Exception
     */
    @Override
    @RabbitListener(queues={AUTO_QUEUE})
    public void onAutoMessage(Message message ) throws Exception {
        log.info("接受到的消息 ：{} count:{}", new String(message.getBody()) , atomicInteger.getAndIncrement());
    }

    /**
     * 发送自动确认的消息
     * @param content
     */
    @Override
    public void sendAutoMsg(String content){
        rabbitTemplate.convertAndSend(AUTO_QUEUE, content);
    }


    /**
     * 发送需要手动确认的消息
     * @param content
     */
    @Override
    public void sendManualMsg(String content) {
        manualRabbitTemplate.convertAndSend(MANUAL_QUEUE, content);
    }


    /**
     * 需要确认的消息接受
     * @param message
     * @param channel
     * @throws Exception
     */
    @Override
    @RabbitListener(queues={MANUAL_QUEUE})
    public void onManualMessage(Message message ,Channel channel ) throws Exception {
        log.info("接受到的消息 ：{} count:{}", new String(message.getBody()) , atomicInteger.getAndIncrement());
        if (atomicInteger.get() % 2 ==0)
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        else
            //multiple：是否批量。 true:将一次性ack所有小于deliveryTag的消息。
            //requeue : 重新放入队列中。
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, false);
    }
}
